// This file is part of gimcopy.
// 
// gimcopy is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
// 
// gimcopy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License along with gimcopy. If not, see <https://www.gnu.org/licenses/>. 

#include <gtk/gtk.h>
void get(GtkClipboard *clipboard, GtkSelectionData *sel, guint info, gpointer data){
  GdkPixbuf *pix = (GdkPixbuf*)data;
  gtk_selection_data_set_pixbuf(sel, pix);
}
void clear(GtkClipboard *clipboard, gpointer data){
  GdkPixbuf *pix = (GdkPixbuf*)data;
  g_object_unref(pix);
}

void cb(GtkClipboard *clipboard, GdkEvent *event, gpointer data){
  GdkEventOwnerChange *ev = (GdkEventOwnerChange*)event;
  if (!gtk_clipboard_get_owner(clipboard)) {
    GdkPixbuf *pix = gtk_clipboard_wait_for_image(clipboard);
    if (pix){
      GtkTargetList *list = gtk_target_list_new(NULL, 0);
      gtk_target_list_add_image_targets(list, 0, TRUE);
      int n_targets;
      GtkTargetEntry *table = gtk_target_table_new_from_list(list, &n_targets);
      gtk_clipboard_set_with_owner(clipboard, table, n_targets, get, clear, G_OBJECT(pix));
      gtk_target_table_free(table, n_targets);
      gtk_target_list_unref(list);
    }
  }
}
int main(int argc, char **argv){
  gtk_init(&argc, &argv);
  GtkClipboard *clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
  g_signal_connect(clipboard, "owner-change", G_CALLBACK(cb), NULL);
  gtk_main();
}
